package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Properties;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        // 参数校验
        if (username != null && password != null){
            // 数据查询， 连接数据库


            String sql = "select * from user where username = ? and password = ?";

            try ( Connection connection = getConnection();
                  PreparedStatement preparedStatement = connection.prepareStatement(sql);){
                preparedStatement.setObject(1, username);
                preparedStatement.setObject(2, password);

                ResultSet resultSet = preparedStatement.executeQuery();

                if (resultSet.next()){
                    // 获取真实姓名
                    String name = resultSet.getString("name");
                    // 登录成功
                    writer.println("<h1>登录成功</h1>");
                    writer.println("<h1>欢迎您，" + name + "</h1>");
                    return;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }



        }
            // 登录失败
//            writer.println("<h1>登录失败, 用户名或密码错误。三秒后跳转到 <a href='index.html'>登录</a> 页面</h1>");
//            response.setHeader("refresh", "3;url=index.html");

            response.sendRedirect("index.html");

    }

    public Connection getConnection(){
        InputStream resourceAsStream = LoginServlet.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            // 加载驱动
            Class.forName((String) properties.get("driver"));
        } catch (ClassNotFoundException e) {
            System.err.println("未加载到驱动 com.mysql.cj.jdbc.Driver");
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;

    }
}
